use axum::Json;
use sea_orm::{ query::*, DatabaseConnection, EntityTrait, FromQueryResult};
use serde::{ Deserialize, Serialize };
use crate::{chrono, query};
#[derive(Debug, Deserialize, Serialize, FromQueryResult)]
pub struct Data {}
// 202408060001 202408070001
pub async fn by_time_day<E:EntityTrait>(conn:&DatabaseConnection, e:E, name:Option<&str>, prefix:&str, start:u8) ->  Result<String, Json<JsonValue>>{
    let no = chrono::now_format(4);
    let start = get_end_num(start);
    let name = if let Some(f) = name { f } else { "no" };
    
    let stmt = Statement::from_string(
        conn.get_database_backend(), 
        format!("select max({}) as max from {} where DATE_FORMAT(CONVERT_TZ(create_time,'+00:00','+08:00'),'%Y%m%d')={}", name, e.table_name(), no)
     );
    if let Some(f) = Data::find_by_statement(stmt).into_json().one(conn).await.unwrap_or_default() {
        if let Some(k) = query::str_op(&f, "max")? {
            Ok(get_num(prefix, k))
        }else {
            Ok(format!("{prefix}{no}{start}"))
        }
    }else{
        Ok(format!("{prefix}{no}{start}"))
    }
}
// 202408060001 202408060002
pub async fn by_time_num<E:EntityTrait>(conn:&DatabaseConnection, e:E, prefix:&str, start:u8, format:usize) ->  Result<String, Json<JsonValue>>{
    let no = chrono::now_format(format);
    let start = get_end_num(start);

    let stmt = Statement::from_string(
        conn.get_database_backend(), 
        format!("select max(no) as max from {}", e.table_name())
     );
    if let Some(f) = Data::find_by_statement(stmt).into_json().one(conn).await.unwrap_or_default() {
        if let Some(k) = query::str_op(&f, "max")? {
            Ok(get_num(prefix, k))
        }else {
            Ok(format!("{prefix}{no}{start}"))
        }
    }else{
        Ok(format!("{prefix}{no}{start}"))
    }
}
// 20240806 - id
pub async fn by_time_id<E:EntityTrait>(conn:&DatabaseConnection, e:E, prefix:&str, split:bool, format:usize) ->  Result<String, Json<JsonValue>>{
    let mut count = 0;

    let stmt = Statement::from_string(
        conn.get_database_backend(), 
        format!("select max(id) as max from {}", e.table_name())
     );

    if let Some(f) = Data::find_by_statement(stmt).into_json().one(conn).await.unwrap_or_default() {
        let max = query::u64_op(&f, "max")?;
        count = max.unwrap_or_default() + 1;
    }
    let rs = if count < 10 { "0".to_owned() + &count.to_string() } else { count.to_string() };
    let s = if split { "-" } else {""};
    Ok( format!("{}{}{}{}", prefix, chrono::now_format(format), s, rs) )
}
// 10000000001
pub async fn by_num<E:EntityTrait>(conn:&DatabaseConnection, e:E, prefix:&str, num:u8) ->  Result<String, Json<JsonValue>>{
    let no = get_start_num(num);
   
    let stmt = Statement::from_string(
        conn.get_database_backend(), 
        format!("select max(no) as max from {}", e.table_name())
     );
    if let Some(f) = Data::find_by_statement(stmt).into_json().one(conn).await.unwrap_or_default() {
        if let Some(k) = query::str_op(&f, "max")? {
            Ok(get_num(prefix, k))
        }else {
            Ok(get_num(prefix, no))
        }
    }else{
        Ok(get_num(prefix, no))
    }
}
// 获取起始编号 1000
fn get_start_num(num:u8) -> String {
    let mut no = String::from("1");
    for _ in 0..num-1 {
        no = no + "0";
    }
    no
}
// 获取起始编号 0001
fn get_end_num(num:u8) -> String {
    let mut no = String::from("");
    for _ in 0..num-1 {
        no = no + "0";
    }
    no + "1"
}

fn get_num(prefix:&str, k:String) -> String {
    if prefix.is_empty() {
        format!("{}", k.parse::<u64>().unwrap_or_default() + 1)
    }else{
        format!("{}{}", prefix, k.replace(prefix, "").parse::<u64>().unwrap_or_default() + 1)
    }
}